package com.example.teacherservice.repository;

import com.example.teacherservice.entity.Question;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.util.List;

// QuestionRepository.java
public interface QuestionRepository extends JpaRepository<Question, Long> {
    List<Question> findByStudentIdAndDeleted(Long studentId, Integer deleted);
    List<Question> findByTeacherIdAndDeleted(Long teacherId, Integer deleted);
    List<Question> findByClassIdAndDeleted(Long classId, Integer deleted);
    List<Question> findByDeleted(Integer deleted);

    // 统一查询用户(学生/教师)的问题
    @Query("SELECT q FROM Question q WHERE " +
            "(q.studentId = :userId OR q.teacherId = :userId)")
    List<Question> findByUserId(@Param("userId") Long userId);


    @Modifying
    @Query("UPDATE Question q SET q.deleted = 1 WHERE q.id = :id AND (q.studentId = :userId OR q.teacherId = :userId)")
    int softDeleteUserQuestion(@Param("id") Long id, @Param("userId") Long userId);

    @Modifying
    @Query("DELETE FROM Comment c WHERE c.questionId = :questionId")
    void deleteCommentsByQuestionId(@Param("questionId") Long questionId);

    @Modifying
    @Query("DELETE FROM QuestionCollection qc WHERE qc.questionId = :questionId")
    void deleteCollectionsByQuestionId(@Param("questionId") Long questionId);

    @Query("SELECT CASE WHEN COUNT(q) > 0 THEN true ELSE false END " +
            "FROM Question q WHERE q.id = :questionId AND " +
            "(q.studentId = :userId OR q.teacherId = :userId)")
    boolean isQuestionBelongsToUser(@Param("questionId") Long questionId,
                                    @Param("userId") Long userId);

    // 在QuestionRepository.java中修改
    @Query("SELECT q FROM Question q WHERE q.teacherId = :teacherId")
    List<Question> findByTeacherId(@Param("teacherId") Long teacherId);
}
